<template>
    <div style=" position: relative;">
        <el-card>
            <template #header>
                <!-- 搜索 -->
                <div style="width:100%;display: flex;">
                    <div style="margin-right:20px">
                        <el-date-picker style="width: 340px;" v-model="data_time" @change="datetime_btn"
                            type="datetimerange" start-placeholder="开始时间" end-placeholder="结束时间"
                            format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss" />
                    </div>
                    <div style="margin-right:20px">
                        <el-input style="width: 220px;" v-model="getWalletListForBack_find_data.note"
                            placeholder="请输入订单详情" clearable prefix-icon="User" />
                    </div>
                    <div style="margin-right:20px"> <el-select style="width: 160px;"
                            v-model="getWalletListForBack_find_data.balType" placeholder="请选择账号类型" clearable>
                            <el-option v-for="item in getBalanceTypes2_list" :key="item.id" :label="item.text"
                                :value="item.id" />
                        </el-select>
                    </div>
                    <div style="margin-right:20px"> <el-select multiple collapse-tags collapse-tags-tooltip
                            style="width: 160px;" v-model="getWalletListForBack_find_data.payTypes"
                            placeholder="请选择交易类型" clearable>
                            <el-option v-for="item in getTradeTypes_list" :key="item.id" :label="item.text"
                                :value="item.id" />
                        </el-select>
                    </div>
                    <div style="margin-right:20px"> <el-select style="width: 120px;"
                            v-model="getWalletListForBack_find_data.tradeStatus" placeholder="请选择收支状态" clearable>
                            <el-option label="收入" value="INCOME" />
                            <el-option label="支出" value="PAY" />
                        </el-select>
                    </div>
                    <div>
                        <el-button style="margin-left: 20px;height:30px" @click="search_btn" type="primary"
                            icon="Search">搜索</el-button>

                    </div>
                </div>
                <!-- 功能按钮 -->
                <div style="margin-top:10px;display:flex;align-items: center;">
                    <el-button @click="wxPayRechargeByQrCode_btn" type="primary" icon="Iphone">充值</el-button>
                    <el-button @click="ex_getWalletListForBack_btn" type="warning" icon="Share">导出</el-button>
                    <div
                        style="display:flex;height:30px;margin-left:20px;align-items: center;background:pink;padding:0 10px">
                        <b style="color:red;font-weight:700">平台余额:{{ cashBalance }}元</b>
                        <el-divider direction="vertical"></el-divider>
                        <b style="color:green;font-weight:700">平台额度:{{ creditBalance }}元</b>
                        <el-divider direction="vertical"></el-divider>
                        <b style="color:red;font-weight:700">车队余额:{{ teamCashBalance }}元</b>
                        <el-divider direction="vertical"></el-divider>
                        <b style="color:green;font-weight:700">车队额度:{{ teamCreditBalance }}元</b>
                        <el-divider direction="vertical"></el-divider>
                        <b style="color:red;font-weight:700">冻结巴士币:{{ freezePointBalance }}</b>
                        <el-divider direction="vertical"></el-divider>
                        <b style="color:green;font-weight:700">正常巴士币:{{ recomPointBalance }}(淡季可抵扣20%现金)</b>

                    </div>
                </div>
            </template>
            <div>
                <el-table border @header-dragend='headerdragend' @selection-change="selection_change_btn" height="67vh"
                    ref="multipleTableRef" :data="getWalletListForBack_list_data" style="width: 100%">
                    <!-- <el-table-column type="selection" width="35" /> -->
                    <el-table-column label="编号" width="55" fixed type="index" />

                    <template v-for="item in table_data_list_new" :key="item.field">
                        <el-table-column v-if="item.off" :width="item.width" :prop="item.field" :label="item.label">
                            <template v-if="item.field == 'payType'" #="{ row, column, $index }">
                                <span>{{ payType_api(row.payType) }}</span>
                            </template>

                            <template v-if="item.field == 'username'" #="{ row, column, $index }">
                                <span>{{ row.companyName }}</span>
                            </template>

                            <template v-if="item.field == 'tradeStatus'" #="{ row, column, $index }">
                                <span>{{ row.tradeStatus == 'INCOME' ? '收入' : '支出' }}</span>
                            </template>



                        </el-table-column>
                    </template>
                </el-table>
            </div>

            <div style="margin-top:20px">
                <el-pagination @current-change="current_change_btn" @size-change="size_change_btn"
                    v-model:current-page="getWalletListForBack_find_data.page.pageNum"
                    v-model:page-size="getWalletListForBack_find_data.page.pageSize" :page-sizes="[100, 200, 300, 500]"
                    :background="true" layout="prev, pager, next, jumper,->,sizes,total," :total="total" />
            </div>
        </el-card>
    </div>
    <!-- 弹窗 -->
    <div>
        <!-- 表格筛选 -->
        <div style="position: absolute;top:100px;z-index: 9999;" :style="icon_off ? 'right:0px;' : 'right:110px;'">
            <el-icon @click="icon_btn" :size="20">
                <Setting />
            </el-icon>
            <div v-show="icon_off"
                style=" position: relative;top:-100px;right:140px;width: 130px;height:430px;background:#fff;overflow: hidden;">
                <div class="cols-set" style="background:#fff;width:90%;height:97%;margin:auto;margin-top:10px;">
                    <div>
                        <el-button-group style="display: flex; ">
                            <el-tooltip effect="dark" placement="bottom">
                                <template #content>注意：拖动下面的项，可以改变表格列的顺序，<br />记得点击保存才会永久生效哦！ </template>
                                <el-button style="width:10px" type="primary" icon="WarningFilled"></el-button>
                            </el-tooltip>
                            <el-button title="重置" type="primary" icon="Refresh" @click="resetTableSet"></el-button>
                            <el-button title="保存" type="primary" icon="Check" @click="saveTableSet"></el-button>
                        </el-button-group>
                        <div ref="sortableContainer" class="col-items" style="height:400px; overflow-y: auto; ">
                            <el-checkbox class="drag_it" @change="checkbox_btn" v-for="item in sortedItems"
                                :key="item.field" v-model="item.off" :label="item.label" border>
                            </el-checkbox>
                        </div>

                    </div>
                </div>
            </div>
        </div>
        <!-- 充值 -->
        <el-dialog style="margin-top:5vh" v-model="wxPayRechargeByQrCode_off" title="充值" width="30%"
            :close-on-click-modal='false'>
            <el-form :inline="true">
                <el-form-item>

                    <el-input style="width: 220px;" type="number" v-model="wxPayRechargeByQrCode_data.rechargeMoney"
                        placeholder="请输入充值金额" clearable />
                </el-form-item>


            </el-form>


            <div style="display: flex;margin-left:20vw">
                <el-button @click="wxPayRechargeByQrCode_ok_btn" type="primary">确认提交</el-button>
            </div>
            <el-dialog append-to-body v-model="weixin_off" title="微信支付" width="30%" :close-on-click-modal='false'>
                <div style="text-align: center;margin-bottom:20px;font-weight:700;font-size:16px;color:#FF6300">
                    扫码支付{{ wxPayRechargeByQrCode_data.rechargeMoney }}元</div>
                <div style="width:200px;height:200px;margin: auto;" id="myQrCode" ref="myQrCode"></div>



                <el-button @click="weixin_pay_ok" style="margin-left:23vw;margin-top:20px"
                    type="warning">我已支付</el-button>

            </el-dialog>
        </el-dialog>
    </div>
</template>

<script setup>
import Sortable from 'sortablejs';
import { ref, reactive, onMounted, computed } from 'vue'
import QRCode from 'qrcodejs2-fix';
import {
    getWalletListForTravel, getTradeTypes2, expWalletListForCompany, adupPrivateSet, getPrivateSetList, getBalanceTypes2,
    companyCusFindById, wxPayRechargeByQrCode,queryWXPayOrder
} from '@/api/transaction_list.js'
import * as XLSX from 'xlsx';
import CircularJSON from 'circular-json'
import { ElMessage, ElLoading, ElMessageBox } from 'element-plus'
onMounted(async () => {

    getPrivateSetList({
        find: '交易记录列表',
        page: {
            pageNum: 1,
            pageSize: 200,
        },
    }).then(res => {
        if (res.data.list[0]) {
            table_data_list_new.value = JSON.parse(res.data.list[res.data.list.length - 1].dat)
        } else {
            table_data_list_new.value = table_data_list
        }
    })

    getBalanceTypes2({}).then(res => {
        getBalanceTypes2_list.value = res.data
    })



    Sortable.create(sortableContainer.value, {
        draggable: '.drag_it',
        ghostClass: 'sortable-ghost',
        onEnd: evt => {
            const targetRow = table_data_list_new.value.splice(evt.oldIndex, 1)[0];
            table_data_list_new.value.splice(evt.newIndex, 0, targetRow);

            // 重新赋值给列数组
            // let cols = that.U.scopy(that.fields);
            // let list = cols.filter(it => { return it.show; });
            // that.$emit('saveSet', {dgName: that.dgName, cols: list});
        }
    })

    await getWalletListForBack_list()
    await getTradeTypes_api()
})
const payType_api = (e) => {
    let data = ''
    for (let i = 0; i < getTradeTypes_list.value.length; i++) {
        if (e == getTradeTypes_list.value[i].id) {
            data = getTradeTypes_list.value[i].text
        }
    }
    return data
}
//#region 表格数据处理
const getBalanceTypes2_list = ref([])
const table_data_list = reactive([
    { label: '客户名称', field: 'username', width: 120, off: true },
    { label: '交易类型', field: 'payType', width: 120, off: true },
    { label: '交易状态', field: 'tradeStatus', width: 100, off: true },
    { label: '交易金额', field: 'amoney', width: 100, off: true },
    { label: '交易后余额', field: 'cashBalance', width: 100, off: true },
    { label: '交易备注', field: 'note', width: '', off: true },
    { label: '交易时间', field: 'addTime', width: 165, off: true },

])

const table_data_list_new = ref([])
const icon_off = ref(false)
// 创建排序容器的引用
const sortableContainer = ref('')

const icon_btn = () => {
    icon_off.value = !icon_off.value
    console.log(sortableContainer.value)

}
const resetTableSet = () => {
    table_data_list_new.value = JSON.parse(JSON.stringify(table_data_list))

}
const saveTableSet = () => {
    console.log({
        dat: JSON.stringify(table_data_list_new.value),
        tbName: '交易记录列表',
        tbNum: "transaction_list",
    })
    adupPrivateSet({
        dat: JSON.stringify(table_data_list_new.value),
        tbName: '交易记录列表',
        tbNum: "transaction_list",
    }).then(res => {
        if (res.code == 1) {
            return ElMessage({
                message: res.msg,
                type: 'success',
            })
        } else {
            return ElMessage({
                message: res.msg,
                type: 'warning',
            })
        }
    })
    icon_off.value = false
}

const checkbox_btn = (e, c) => {
    for (let i = 0; i < table_data_list_new.value.length; i++) {
        if (table_data_list_new.value[i].label == c.target._value) {
            table_data_list_new.value[i].off == e

        }

    }

}

const sortedItems = computed(() => {
    return [...table_data_list_new.value].sort((a, b) => a.id - b.id);
})
//#endregion

//#region 充值
const wxPayRechargeByQrCode_off = ref(false)
const wxPayRechargeByQrCode_data = reactive({
    rechargeMoney: null,
})
const wxPayRechargeByQrCode_btn = () => {
    wxPayRechargeByQrCode_data.rechargeMoney = null
    wxPayRechargeByQrCode_off.value = true
}
const myQrCode = ref('')
const weixin_off = ref(false)
const weixin_data = ref({})
const weixin_pay_ok = () => {
    queryWXPayOrder({ orderPayNum: weixin_data.value.out_trade_no }).then(res => {
        if (res.code == '1') {
            if (res.data.trade_state_desc == '订单未支付') {
                
                return ElMessage({
                    message: res.data.trade_state_desc,
                    type: 'warning',
                })
            } else {
                weixin_off.value = false
                wxPayRechargeByQrCode_off.value = false
               
                getWalletListForBack_list()

                return ElMessage({
                    message: res.data.trade_state_desc,
                    type: 'success',
                })
            }

        }



    })
}
const generateCode = (codeUrl) => {
    document.getElementById("myQrCode").innerHTML = ""
    try {
        new QRCode(myQrCode.value, {
            width: 200, //宽度
            height: 200, // 高度
            text: codeUrl, // 二维码内容
        })
    } catch (e) {
        console.log(e)
    }
}
const wxPayRechargeByQrCode_ok_btn = () => {
    ElMessageBox.confirm(
        `是否确认充值金额?`,
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
            distinguishCancelAndClose: 'true',
        }
    )
        .then(() => {
            wxPayRechargeByQrCode(wxPayRechargeByQrCode_data).then(res => {
                if (res.code == 1) {
                    weixin_data.value = res.data
                    weixin_off.value = true
                    setTimeout(() => {
                        generateCode(res.data.code_url)
                    }, 500);

                } else {
                    return ElMessage({
                        message: res.msg,
                        type: 'warning',
                    })
                }
            })
        })
        .catch((e) => {


        })

}

//#endregion




//#region 分页列表
const getWalletListForBack_list_data = ref([])
const getWalletListForBack_find_data = reactive({
    page: {
        pageNum: 1,
        pageSize: 200,
    },
    stime: "",
    etime: "",
    note: "",
    payTypes: ['ORDER_PAY', 'ORDER_REFUND'],
    balType: 'CASH_BALANCE',
    tradeStatus: '',

})
const total = ref(0)

// 分页器一夜显示多少数据页面
const size_change_btn = () => {
    getWalletListForBack_find_data.page.pageNum = 1
    getWalletListForBack_list()
}

// 分页器跳转页面
const current_change_btn = () => {
    getWalletListForBack_list()
}
const teamCashBalance = ref(0)
const teamCreditBalance = ref(0)
const cashBalance = ref(0)
const creditBalance = ref(0)
const freezePointBalance = ref(0)
const recomPointBalance = ref(0)
const getWalletListForBack_list = () => {
    const loading = ElLoading.service({
        lock: true,
        text: '正在加载，中请稍后...',
        background: 'rgba(0, 0, 0, 0.7)',
    })
    getWalletListForTravel(getWalletListForBack_find_data).then(res => {
        loading.close()
        getWalletListForBack_list_data.value = res.data.list.list
        teamCashBalance.value = res.data.teamCashBalance
        teamCreditBalance.value = res.data.teamCreditBalance
        cashBalance.value = res.data.cashBalance
        creditBalance.value = res.data.creditBalance
        freezePointBalance.value = res.data.freezePointBalance
        recomPointBalance.value = res.data.recomPointBalance
        total.value = res.data.list.total
    })
}
//#endregion

//#region 表格选择
const table_list = ref([])
const headerdragend = (newWidth, oldWidth, column) => {
    console.log(newWidth, oldWidth, column)
    for (let i = 0; i < table_data_list_new.value.length; i++) {
        if (column.property == table_data_list_new.value[i].field) {
            table_data_list_new.value[i].width = newWidth
        }
    }
}
const selection_change_btn = (e) => {
    table_list.value = e
    console.log('表格选择的数据', e)
}
//#endregion

//#region 搜索
const data_time = ref([])
const datetime_btn = (e, y, c) => {
    console.log(data_time.value)
    if (data_time.value) {
        getWalletListForBack_find_data.stime = data_time.value[0]
        getWalletListForBack_find_data.etime = data_time.value[1]
    } else {
        getWalletListForBack_find_data.stime = ''
        getWalletListForBack_find_data.etime = ''
    }

}

// 交易类型
const getTradeTypes_list = ref([])
const getTradeTypes_api = () => {
    getTradeTypes2({}).then(res => {
        getTradeTypes_list.value = res.data
    })
}

const search_btn = () => {
    localStorage.setItem('transaction_list', CircularJSON.stringify(getWalletListForBack_find_data))
    getWalletListForBack_list()
}
//#endregion
//#region 交易记录列表导出
const ex_getWalletListForBack_btn = () => {
    // 
    let ps = {
        page: {
            pageNum: 1,
            pageSize: total.value,
        },
        stime: getWalletListForBack_find_data.stime,
        etime: getWalletListForBack_find_data.etime,
        note: getWalletListForBack_find_data.note,
        payTypes: getWalletListForBack_find_data.payTypes,
        balType: getWalletListForBack_find_data.balType,
        tradeStatus: getWalletListForBack_find_data.tradeStatus,
    }
    expWalletListForCompany(ps).then(res => {
        if (res.code == 1) {
            const data = [
                ['客户名称', '交易类型', '交易状态', '交易金额', '交易后余额', '交易备注', '交易时间',],
            ];
            for (let i = 0; i < res.data.list.list.length; i++) {
                let ps = {
                    username: res.data.list.list[i].companyName,
                    payType: payType_api(res.data.list.list[i].payType),
                    tradeStatus: res.data.list.list[i].tradeStatus == 'INCOME' ? '收入' : '支出',
                    amoney: res.data.list.list[i].amoney,
                    cashBalance: res.data.list.list[i].cashBalance,
                    note: res.data.list.list[i].note,
                    addTime: res.data.list.list[i].addTime,

                }
                console.log(ps, 'pspsps')
                data.push(Object.values(ps))
            }
            const ws = XLSX.utils.aoa_to_sheet(data);
            const wb = XLSX.utils.book_new();
            XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');
            XLSX.writeFile(wb, '单位管理后台系统-钱包记录列表.xlsx');
            getWalletListForBack_list()
            return ElMessage({
                message: res.msg,
                type: 'success',
            })
        } else {
            return ElMessage({
                message: res.msg,
                type: 'warning',
            })
        }

    })
}
//#endregion
</script>

<style scoped lang='scss'></style>
<style>
.el-table .el-table__cell {
    padding: 0px !important;
}

.col-items::-webkit-scrollbar {
    width: 5px !important;
}

.col-items>label {
    margin-left: 0px !important;
    margin-top: 5px;
    width: 100%;
}
</style>
